package com.bruce.ssm.base;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseHibernateDao {
    @Autowired
    SessionFactory sessionFactory;
    /***模拟HibernateSessionFactory保存当前的Session**/
    protected static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    protected SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    protected void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession() {
        Session session = threadLocal.get();
        if (session == null || !session.isOpen()) {
            session = sessionFactory.openSession();
            //session.setFlushMode(FlushMode.AUTO);
            threadLocal.set(session);
        }
        return session;
    }

    protected void closeSession() {
        Session session = threadLocal.get();
        if (session != null) {
            //session.flush();
            session.close();
        }
    }
}
